// 通过 vue-router 插件实现模板路由配置
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoute } from './routes'

// 创建路由器
let router = createRouter({
    history: createWebHashHistory(),
    routes: constantRoute,
    // 滚动行为
    scrollBehavior() {
        return {
            left: 0,
            top: 0
        }
    }
})

// 清理localStorage的函数
const cleanupLocalStorage = () => {
    // localStorage.removeItem('TOKEN')
    // localStorage.removeItem('satellites')
    // localStorage.removeItem('groundStations')
    // localStorage.removeItem('areaTargets')
    // localStorage.removeItem('pointTargets')
    // localStorage.removeItem('payloads')
    // localStorage.removeItem('currentScene')
    // localStorage.removeItem('cesium-hasSeenNavHelp')
}

// 页面关闭时清理localStorage
window.addEventListener('beforeunload', cleanupLocalStorage)

// 路由销毁时移除监听器
router.afterEach(() => {
    return () => {
        window.removeEventListener('beforeunload', cleanupLocalStorage)
    }
})

// 导航守卫
router.beforeEach((to, from, next) => {
    // 假设用户登录状态通过 localStorage 中的 'TOKEN' 来判断
    const isLoggedIn = localStorage.getItem('TOKEN');

    // 如果目标路由不是登录页且用户未登录
    if (to.name!== 'login' && !isLoggedIn) {
        next({ name: 'login' });
    } else {
        next();
    }
});

export default router;
